package com.ccc.boot.system.service.impl;

import com.ccc.boot.base.BaseServiceImpl;
import com.ccc.boot.constant.DictConstant;
import com.ccc.boot.exception.BusinessException;
import com.ccc.boot.redis.util.RedisUtils;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.response.ResponseResult;
import com.ccc.boot.system.entity.SysRole;
import com.ccc.boot.system.mapper.SysRoleMapper;
import com.ccc.boot.system.pojo.AuthorizeApiParam;
import com.ccc.boot.system.pojo.AuthorizeMenuParam;
import com.ccc.boot.system.service.RelRoleResourceService;
import com.ccc.boot.system.service.RelUserRoleService;
import com.ccc.boot.system.service.SysApiService;
import com.ccc.boot.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 接口资源表 业务处理实现类
 *
 * @author superC
 * @version 0.1.0
 * @date 2022-03-30
 */
@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private RelUserRoleService relUserRoleService;

    @Autowired
    private RelRoleResourceService relRoleResourceService;

    @Autowired
    private SysApiService sysApiService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        try {
            if (!checkId(id)) {
                throw new BusinessException(ResponseCode.RESULT_DATA_NONE);
            }
            // 删除用户角色中间表
            relUserRoleService.deleteByRoleId(id);

            // 删除角色表
            return super.removeById(id);
        } catch (Exception e) {
            logger.error("【捕获异常-删除操作】\r\n异常记录：", e);
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException(ResponseCode.DATA_DELETE_FAILURE);
        }
    }

    /**
     * 授权菜单资源
     *
     * @param param
     * @return {@link ResponseResult}
     * @date 2022/4/2 13:17
     * @author superC
     */
    @Override
    public boolean authorizeMenu(AuthorizeMenuParam param) {
        Long roleId = param.getRoleId();
        if (relRoleResourceService.check(roleId)) {
            // 先删除原有菜单资源权限
            relRoleResourceService.deleteResource(roleId);
        }

        // 再重新添加菜单资源
        if (param.getMenuIds() != null && param.getMenuIds().size() > 0) {
            param.getMenuIds().forEach(menuId -> {
                relRoleResourceService.insert(roleId, DictConstant.RESOURCE_TYPE_MENU, menuId);
            });
        }

        return true;
    }

    @Override
    public boolean authorizeApi(AuthorizeApiParam param) {
        Long roleId = param.getRoleId();

        // 先根据菜单id获取所有按钮资源
        List<Long> apiIds = sysApiService.getEnabledApiIds(param.getMenuId());
        if (apiIds == null) {
            return false;
        }

        // 先删除原有按钮接口权限
        relRoleResourceService.deleteApis(roleId, apiIds);

        // 再添加按钮接口资源
        if (param.getApiIds() != null && param.getApiIds().size() > 0) {
            relRoleResourceService.insertApis(roleId, param.getApiIds());
        }

        // 清除缓存
        sysApiService.resetCache2Apis();

        return true;
    }

    @Override
    public List<String> getRoleCodes(Long userId) {
        return baseMapper.getRoleCodes(DictConstant.STATUS_ENABLE, userId);
    }

}
